package com.mingqijia.gassafety.webserver.listeners;

import com.mingqijia.gassafety.webserver.service.workorder.SkWorkOrderService;
import com.mingqijia.gassafety.webserver.utils.ApplicationContextUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 工单自动创建消息监听
 * @author: duanhongxiang
 * @Desc:
 * @create: 2024-09-03 18:04
 **/
@Component
@Slf4j
public class OrderAutoGenMessageListener implements MessageListener {
    private static final String split = ";;";

    @SneakyThrows
    @Override
    public void onMessage(Message message, byte[] bytes) {
        log.info("OrderAutoGenMessageListener:监听到redis消息：{}", message);
        byte[] body = message.getBody();
        if (body.length > 0) {
            String mess = new String(message.getBody(), StandardCharsets.UTF_8).trim().replaceAll("\\\\", "");
            if (mess.length() >= 2) mess = mess.substring(1, mess.length() - 1);
            // 发送消息
            if (mess.contains(split)) {
                String[] split = mess.split(OrderAutoGenMessageListener.split);
                mess = split[0];
                SkWorkOrderService skWorkOrderService = ApplicationContextUtils.getBean(SkWorkOrderService.class);
                if (skWorkOrderService != null) {
                    skWorkOrderService.autoCreateOrderByMsg(split[1],mess);
                }else{
                    log.error("skWorkOrderService is null");
                }
            }
        }
    }


}
